package com.test.textGame.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.textGame.enums.MqLogTypeEnum;
import com.test.textGame.service.MqFailLogService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import com.test.textGame.algorithm.TopK;
import com.test.textGame.dao.Top10Dao;
import com.test.textGame.domain.Player;
import com.test.textGame.domain.Top10;
import com.test.textGame.mq.RabbitSlaverProducer;
import com.test.textGame.service.Top10Service;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Auto created by codeAppend plugin
 */
@Service
public class Top10ServiceImpl extends ServiceImpl<Top10Dao, Top10> implements Top10Service {

    @Autowired
    private RabbitSlaverProducer rabbitSlaverProducer;
    @Autowired
    DefaultMQProducer producer;
    @Value("rocketmq.slaver.consumer.topics")
    private String topics;
    @Autowired
    private MqFailLogService mqFailLogService;

    private static final TopK topK = new TopK(10);

    @Override
    public void updateHeap(Player player, Integer gameScore) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        //比较分数大小并更新排行榜
        TopK.Node sendMsg = topK.add(player, gameScore);

        //如果排行榜发生变动，将新进入的分数和玩家发送给master
        if (sendMsg != null) {
            //为了限速，改用rocketMq，用拉取模式消费消息
            String msg = JSONObject.toJSONString(sendMsg);
            Message message = new Message(topics, msg.getBytes());
            try {
                producer.send(message);
            } catch (Exception e) {
                System.out.println("给master发消息失败e:"+e);
                mqFailLogService.saveLog(MqLogTypeEnum.SEND_MASTER_FAIL, msg);
            }

            //rabbitMq方式发生消息
//            try {
//                rabbitSlaverProducer.sendPlayerScore(sendMsg);
//            } catch (Exception e) {
//                System.out.println("给master发消息失败e:"+e);
//                mqFailLogService.saveLog(MqLogTypeEnum.SEND_MASTER_FAIL, msg);
//            }
        }

    }
}